package ltd.hyangyang.vegetable.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/ws/train")
public class WebSocketServer {

    private Session session;

    private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>();


    @OnOpen
    public void onOpen(Session session){
        System.out.println("连接成功");
        webSocketSet.add(session);

    }

    @OnClose
    public void onClose(Session session){
        System.out.println("连接已断开");
        webSocketSet.remove(session);
    }

    @OnMessage
    public void onMessage(String message){
        //后端收到前端发送的消息
    }

    public  void sendMessage(String message,Session session){
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessageToAll(String message){
        for (Session session : webSocketSet) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
